<template>
	<view>
		<view v-if="isLogin">
			<view class="head-container">
				<!-- 修正1：img-avatar的src绑定data中的avatar变量 -->
				<image :src="avatar" mode="aspectFill" class="img-avatar"></image>
				<view class="info-container">
					<view class="nick-container">
						<!-- 修正2：txt-nick绑定nickName变量 -->
						<text class="txt-nick">{{ nickName + "-[" + uTypes[type-1] + "]" }}</text>
						<!-- 修正3：img-badge的src绑定badges数组（根据type索引） -->
						<image :src="badges[type-1]" mode="widthFix" class="img-badge"></image>
					</view>
					<!-- 修正4：txt-user绑定userName或email（根据需求选择） -->
					<text class="txt-user">{{ userName+":"+email }}</text>
				</view>
			</view>
                      <text class="iconfont icon-yonghu txt-logout" @click="clickLogout"></text>
			<view class="data-container">
				<!-- 点赞的文章，使用滚动视图 -->
				<view class="data-title" @click="clickSwitch(0)">
					<text class="data-title-name">我点赞的{{goodCount}}文章</text>
					<text :class="status[0].open?'iconfont icon-shouye ics-arrow':'iconfont icon-shouye-xianxing ics-arrow' "></text>
				</view>
				 <scroll-view scroll-x v-if="status[0].open" class="scroll-scroll" scroll-with-animation="true" @scrolltolower="getMoreBlogs" >
					 <view class="scroll-item" v-for="(blog,indx) in goodBlogs" :key="blog.id" @click="clickGoBlog(blog.id)">
						 <image :src="blog.picture" mode="aspectFill"></image>
						 <text>{{blog.title}}</text>
					 </view>
				 </scroll-view>
			</view>
			
			<view class="data-container">
				<!-- 管理类的数据，使用文本标签 -->
				<view class="data-title" @click="clickSwitch(1)">
					<text class="data-title-name">我管理的{{categories.length}}个类别数据</text>
					<text :class="status[1].open?'iconfont icon-shouye ics-arrow':'iconfont icon-shouye-xianxing ics-arrow' "></text>
				</view>
				 <view v-if="status[1].open" class="category-container">
					<view class="category-item" v-for="(c,index) in categories" :key="c.id">
						<text class="category-name" @click="clickUpdate(c.id,c.name)">{{c.name}}</text>
						<text :class="c.count==0? 'btn-category':'num-category' " @click="c.count==0?clickDelete(c.id,c.name):''">{{c.count==0?'X':c.count}}</text>
					</view>
					 <view class="category-item">
						 <text class="iconfont icon-tianranqi txt-add" @click="clickAdd"></text>
					 </view>
				 </view>
			</view>
		</view>
		
		<login-dialog ref="login" @login="afterLogin"></login-dialog>
		<dialog-shell ref="shell_update"  title="更新类别名称" @confirm="confirmUpdate">
			<view style="margin: 10rpx;">
				<input type="text" :value="oldValue" @input="inputGetValue" placeholder="请输入新的名称" style="padding-left: 15rpx;npm cache clean --force"/>
			</view>
		</dialog-shell>
		<dialog-shell ref="shell_add"  title="更新类别名称" @confirm="confirmAdd">
			<view style="margin: 10rpx;">
				<input type="text" focus="" @input="inputGetValue" placeholder="请输入新的名称" style="padding-left: 15rpx;npm cache clean --force"/>
			</view>
		</dialog-shell>
	</view>
</template>

<script>
	import LoginDialog from '@/components/dialog-shell/login-dialog.vue'
	import DialogShell from '@/components/dialog-shell/dialog-shell.vue'
	export default {
		components: {
					LoginDialog,
					DialogShell
				},
		data() {
			return {
				isLogin: false,
				avatar: '', // 建议设置默认头像路径（如：'/static/default_avatar.png'）
				userName: '', // 建议初始化默认值（如：'未设置用户名'）
				email: '',
				nickName: '', // 建议初始化默认值（如：'未设置昵称'）
				uTypes: ['管理员', '认证博主', '博客会员'],
				type: -1, // 确保type在0-2范围内（否则badges数组会越界）
				badges: [
					'../../static/icons(1)/badge0.png',
					'../../static/icons(1)/badge1.png',
					'../../static/icons(1)/badge2.png'
				],
				status:[{open:false},{open:false},{open:false},{open:false}],
				goodCount:-1,
				goodBlogs:[],
				goodIds:[],
				page:0,
				size:2,
				categories:[],
				oldValue:'',
				newValue:'',
				updateId:''
				
			}
		},
		mounted() {
			if (getApp().globalData.token.length==0) {
				this.$refs.login.show()
			}
		},
		onLoad() {
			this.$noti.add(this.$params.noti_login_status,this.afterLogin,this)
		    this.isLogin=getApp().globalData.token.length>0
			if(this.isLogin){
				this.initUser()
			}
			this.getLocalGood()
		},
		onShow(){
			this.loadData()
		},
		methods: {
			clickDelete(id,name){
			  let url =this.$params.host+this.$params.action_category_del+id
			  let data={
				  token:getApp().globalData.token
			  }
			  uni.showModal({
			  	title:'确认',
				content:'确认要删除'+name+'吗?',
				showCancel:true,
				cancelText:'再想想',
				confirmText:'删除',
				success: res => {
					 if(res.confirm){
						 this.$req.del(url,data,res=>{
							 // console.log(res);
							 if(res.data.success){
								 this.categories=this.categories.filter(c=>c.id!=id)
							 }else{
								 uni.showToast({
								 	title:res.data.message,
									icon:'none'
								 });
							 }
						 })
					 }
				},
				fail: () => {},
				complete: () => {}
			  });
			},
			confirmAdd(){
			if(this.newValue.trim().length==0){
				uni.showToast({
					title:'请输入新的类别名称',
					icon:'none'
				});
				return
			}
			let url=this.$params.host+this.$params.action_category_add
			let data={
				token:getApp().globalData.token,
				name:this.newValue
			}
			this.$req.request(url,data,'POST')
			.then(res=>{
				if(!res.success){
					uni.showToast({
						title:res.message
					});
					return
				}
				let item={
					id:res.data.id,
					name:res.data.name,
					count:0
				}
				this.categories.push(item)
				this.newValue=''
			})
			.catch(err=>{
				console.log(err);
			})
			},
			clickAdd(){
				this.$refs.shell_add.showDialog()
			},
			confirmUpdate(){
				if(this.newValue.trim().length==0){
					uni.showToast({
						title:'请输入新的类别名称',
						icon:'none'
					});
					return
				}
				let url =this.$params.host+this.$params.action_category_put+this.updateId
				let data={
					token:getApp().globalData.token,
					name:this.newValue
				}
				this.$req.request(url,data,'PUT')
				.then(res=>{
					if(!res.success){
						uni.showToast({
							title:res.message
						});
						return
					}
					let item=res.data
					this.categories.forEach(c=>{
						if(c.id==item.id){
							c.name=item.name
						}
					})
					this.newValue=''
				})
				.catch(err=>{
					console.log(err);
				})
			},
			clickUpdate(id,name){
				this.oldValue=name
				this.updateId=id
				this.$refs.shell_update.showDialog()
			},
			inputGetValue(e){
				this.newValue = e.detail.value 
			},
			afterLogin() {
				if (this.isLogin) {
					return}
				this.initUser()
				this.loadData()
				
			},
			initUser(){const app = getApp();
				this.isLogin = app.globalData.token.length > 0;
				this.avatar=this.$params.host+app.globalData.avatar
				this.userName=app.globalData.userName
				this.email=app.globalData.email
				this.nickName=app.globalData.nickName
				this.type=app.globalData.type
				// console.log(app.globalData)
				},
		    loadData(){
				this.page=0
				this.goodBlogs=[]
				this.goodCount=-1
			    this.getLocalGood()
				for(let i=0;i<this.size;i++){
					this.getMoreBlogs()
				}
				this.getCategories()
			},
			clickSwitch(index){
				let now=this.status[index].open
				this.status[index].open=!now
			},
			getLocalGood(){
				let ids=uni.getStorageSync(this.$params.key_good_ids)
				if(ids){
					this.goodIds=ids
				}
				this.goodCount=ids.length
			},
			getMoreBlogs() {
				if (this.goodCount >= 0 && this.goodBlogs.length == this.goodCount) {
					return;
				}
				if (!this.goodIds || this.page >= this.goodIds.length || !this.goodIds[this.page]) {
					return;
				}
				let url = this.$params.host + this.$params.action_top_blogs + this.goodIds[this.page++];
				this.$req.get(url, res => {
					console.log(res);
					let blog = res.data.data;
					blog.picture = this.$params.host + blog.picture;
					this.goodBlogs = this.goodBlogs.concat(blog);
				});
			},
			getCategories(){
			  	let url=this.$params.host +this.$params.action_categories
			     this.$req.get(url,res=>{
					 this.categories=[]
					 url =this.$params.host+this.$params.action_category_count
					 res.data.data.forEach(async(c)=>{
						 let r =await 
						 this.$req.request(url+c.id)
						 if(res.data.success){
							 let category={
								 id:c.id,
								 name:c.name,
								 count:c.data
							 }
							 this.categories.push(category)
						 }
					 })
				 })
			},
			clickGoBlog(id){
				uni.navigateTo({
					url: '../blog/blog?id='+id,
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			clickLogout(){
				let url =this.$params.host+this.$params.action_logout
				let app=getApp()
				let data={
					token:app.globalData.token
				}
				this.$req.postQuery(url,data,res=>{
					uni.showToast({
						title:res.data.message,
						icon:'none'
					});
				if(res.data.success){
					app.globalData.token=''
					app.globalData.id=''
					app.globalData.avatar=''
					app.globalData.nickName=''
					app.globalData.userName=''
					app.globalData.email=''
					app.globalData.type=-1
					this.isLogin=false
					this.$refs.login.show()
					this.goodBlogs=[]
					this.page=0
					this.goodCount=-1
				}	
				})
			}
		}
	}
</script>

<style>
@import url("profile.css");
</style>